package com.wibo.common;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import com.wibo.account.R;
import com.wibo.account.WiboMainActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

public class Utility {
	private static final String TAG = "Utility";
	
	public static final int USER_PIC = 0;
	public static final int THUMBNAIL_PIC = 1;
	public static final int MIDDLE_PIC = 2;
	public static final int LARGE_PIC = 3;
	public static final int LARGE_USER_PIC = 4;
	public static final int WEIBO_LOCATION_PIC = 5;
	
	public static final int USER_UNKNOW = -1;
	public static final int USER_MYSELF = 0;
	public static final int USER_FOLLOW = 1;
	public static final int USER_FRIEND = 2;
	public static final int USER_UNFRIEND = 3;
	
	public static final String WEIBO_PIC = "Weibo_pic";
	public static final String WEIBO_MID_PIC = "Weibo_mid_pic";
	public static final String WEIBO_LARGE_PIC = "Weibo_large_pic";
	public static final String COMMENT_PIC = "Comment_pic";
	public static final String LOCATION_PIC = "Location_pic";
	
	public static final String ENG_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,./;' []\\<>?:\"{}|`-=~!@#$%^&*()_+";
	
	public static final long REFRESH_INTERVAL = 120;
	
	public static String mUserName = "defaut";
	
    /**
     * 获取等待对话框
     * 
     * @param context
     *            ，调用该对话框所在activity的context对象
     *            
     *  sample:使用show()开始等待，使用cancle()结束等待(注意，如果同一个progressDialog需要再次使用,则使用hide()隐藏)
     */
    
    public static ProgressDialog getWaitDialog(Context context, String text){
    	ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage(text);
		progressDialog.setIndeterminate(false);
		progressDialog.setCancelable(true);
		progressDialog.setCanceledOnTouchOutside(false);
		return progressDialog;
    }
    
    /**
	 * Returns whether the network is available for Activity or Service
	 */
	public static boolean isNetworkAvailable( Context context){
		ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if( connectivity == null ){
			return false;
		}else{
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if( info != null ){
				for( int i = 0;i < info.length;i++){
					if( info[i].getState() == NetworkInfo.State.CONNECTED ){
//						String extraInfo = info[i].getExtraInfo();
//						if( extraInfo != null && extraInfo.toUpperCase().contains("CMWAP")){
//							// wap 网络
//							// 可根据情况获取对应的信息
//							String data = info[i].toString();
//							// 设置HttpClient的proxy值
//							HttpClient.setProxyHost("10.0.0.172");
//							HttpClient.setProxyPort(80);
//						}else{
//							HttpClient.setProxyHost("");
//							HttpClient.setProxyPort(0);
//						}
						return true;
					}
				}
			}
		}
		
        return false;
    }
	
	public static final String LOCATION_STATIC_PIC_BAIDU = "http://api.map.baidu.com/staticimage?center=%s,%s&width=400&height=300&zoom=18";
	//public static final String LOCATION_STATIC_PIC_GOOGLE = "http://maps.google.com/maps/api/staticmap?center=%s,%s&zoom=12&size=400x300&maptype=roadmap&sensor=true";
	public static String getLocationUrl(String lo, String la) {
		String url = String.format(LOCATION_STATIC_PIC_BAIDU, lo, la);
		return url;
	}
	
	public static boolean isImageExist(Context context, String url, String dirName, int picType) {
		if (url == null)
			return false;
		String imagePath = "";
		String fileName = "";

		// 获取url中图片的文件名与后缀
		switch (picType) {
		case USER_PIC:
			if (url != null && url.length() != 0) {
				int pos1 = url.indexOf(".cn/");
				int pos2 = url.indexOf("/", pos1 + 4);
				fileName = url.substring(pos1 + 4, pos2 - 1); // url.lastIndexOf("/")+1
			}
			break;
		case THUMBNAIL_PIC:
		case MIDDLE_PIC:
		case LARGE_PIC:
			fileName = url.substring(url.lastIndexOf("/") + 1);
			break;
		case LARGE_USER_PIC:
			if (url != null && url.length() != 0) {
				int pos1 = url.indexOf(".cn/");
				int pos2 = url.indexOf("/", pos1 + 4);
				fileName = url.substring(pos1 + 4, pos2 - 1) + "_180"; // url.lastIndexOf("/")+1
			}
			break;
		case WEIBO_LOCATION_PIC:
			imagePath = "/sdcard/wibo_cache" + "/" + mUserName + "/" + LOCATION_PIC + "/" + dirName + ".png";
			break;
		}
		
		if (picType != WEIBO_LOCATION_PIC) {
			//判断sd卡是否存在 
			boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
			if (sdCardExist){ 
				imagePath = "/sdcard/wibo_cache" + "/" + mUserName + "/" + dirName + "/";
				File destDir = new File(imagePath);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
			}else{
				// 图片在手机本地的存放路径,注意：fileName为空的情况
				imagePath = context.getCacheDir() + "/" + mUserName + "/" + dirName + "/";
				File destDir = new File(imagePath);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
			}
			imagePath += fileName;
		}
		
		Log.i(TAG, "imagePath = " + imagePath);
		File file = new File(imagePath);// 保存文件,context.getCacheDir(), fileName
		if (!file.exists()) {
			return false;
		}
		return true;
	}
	
	public static String getPicPath(Context context, String url, String dirName, int picType) {
		if (url == null)
			return null;
		String imagePath = "";
		String fileName = "";

		// 获取url中图片的文件名与后缀
		switch (picType) {
		case USER_PIC:
			if (url != null && url.length() != 0) {
				int pos1 = url.indexOf(".cn/");
				int pos2 = url.indexOf("/", pos1 + 4);
				fileName = url.substring(pos1 + 4, pos2 - 1); // url.lastIndexOf("/")+1
			}
			break;
		case THUMBNAIL_PIC:
		case MIDDLE_PIC:
		case LARGE_PIC:
			fileName = url.substring(url.lastIndexOf("/") + 1);
			break;
		case LARGE_USER_PIC:
			if (url != null && url.length() != 0) {
				int pos1 = url.indexOf(".cn/");
				int pos2 = url.indexOf("/", pos1 + 4);
				fileName = url.substring(pos1 + 4, pos2 - 1) + "_180"; // url.lastIndexOf("/")+1
			}
			break;
		case WEIBO_LOCATION_PIC:
			imagePath = "/sdcard/wibo_cache" + "/" + mUserName + "/" + LOCATION_PIC + "/" + dirName + ".png";
			break;
		}
		
		if (picType != WEIBO_LOCATION_PIC) {
			//判断sd卡是否存在 
			boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
			if (sdCardExist){ 
				imagePath = "/sdcard/wibo_cache" + "/" + mUserName + "/" + dirName + "/";
				File destDir = new File(imagePath);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
			}else{
				// 图片在手机本地的存放路径,注意：fileName为空的情况
				imagePath = context.getCacheDir() + "/" + mUserName + "/" + dirName + "/";
				File destDir = new File(imagePath);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
			}
			imagePath += fileName;
		}
		Log.i(TAG, "imagePath = " + imagePath);
//		File file = new File(imagePath);// 保存文件,context.getCacheDir(), fileName
//		if (!file.exists()) {
//			return WiboMainActivity.LOADING_PIC;
//		}
		return imagePath;
	}
	

	
	// 获取网络图片，如果缓存里面有就从缓存里面获取
	public static String getImagePath(Context context, String url, String dirName, int picType) {
		if (url == null)
			return "";
		String imagePath = "";
		String fileName = "";

		// 获取url中图片的文件名与后缀
		switch (picType) {
		case USER_PIC:
			if (url != null && url.length() != 0) {
				int pos1 = url.indexOf(".cn/");
				int pos2 = url.indexOf("/", pos1 + 4);
				fileName = url.substring(pos1 + 4, pos2 - 1); // url.lastIndexOf("/")+1
			}
			break;
		case THUMBNAIL_PIC:
		case MIDDLE_PIC:
		case LARGE_PIC:
			fileName = url.substring(url.lastIndexOf("/") + 1);
			break;
		case LARGE_USER_PIC:
			if (url != null && url.length() != 0) {
				int pos1 = url.indexOf(".cn/");
				int pos2 = url.indexOf("/", pos1 + 4);
				fileName = url.substring(pos1 + 4, pos2 - 1) + "_180"; // url.lastIndexOf("/")+1
			}
			break;
		case WEIBO_LOCATION_PIC:
			imagePath = "/sdcard/wibo_cache" + "/" + mUserName + "/" + LOCATION_PIC + "/";
			File destDir = new File(imagePath);
			if (!destDir.exists()) {
				destDir.mkdirs();
			}
			imagePath += (dirName + ".png");
			break;
		}
		
		if (picType != WEIBO_LOCATION_PIC) {
			//判断sd卡是否存在 
			boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
			if (sdCardExist){ 
				imagePath = "/sdcard/wibo_cache" + "/" + mUserName + "/" + dirName + "/";
				File destDir = new File(imagePath);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
			}else{
				// 图片在手机本地的存放路径,注意：fileName为空的情况
				imagePath = context.getCacheDir() + "/" + mUserName + "/" + dirName + "/";
				File destDir = new File(imagePath);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
			}
			imagePath += fileName;
		}
		Log.i(TAG, "imagePath = " + imagePath);
		File file = new File(imagePath);// 保存文件,context.getCacheDir(), fileName
		if (!file.exists()) {
			Log.i(TAG, "file 不存在 ");
			try {
				byte[] data = readInputStream(getRequest(url));
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
						data.length);

				bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(
						file));

				imagePath = file.getAbsolutePath();
				Log.i(TAG, "imagePath : file.getAbsolutePath() = " + imagePath);

			} catch (Exception e) {
				Log.e(TAG, e.toString());
				return null;
			}
		}
		return imagePath;
	} // getImagePath( )结束。
	
	public static Bitmap mDefaultPic = null;
	
	public static Bitmap getDefaultPic(Context context){
		if (mDefaultPic != null){
			return mDefaultPic;
		}else{
			Drawable d = context.getResources().getDrawable(R.drawable.weibo_pic);
			BitmapDrawable bd = (BitmapDrawable)d;

			Bitmap bm = bd.getBitmap();
			return bm;
		}
	}
	
	public static Bitmap getBitmap(Context context, String url, String dirName, int picType){
		String path = getPicPath(context, url, dirName, picType);
		if (path == null) {
			return getDefaultPic(context);
		}
		File file = new File(path);// 保存文件,context.getCacheDir(), fileName
		if (!file.exists() || file.isDirectory()) {
			return getDefaultPic(context);
		}
		
		return BitmapFactory.decodeFile(path);
	}
	
	public static InputStream getBytes(Context context, String url, String dirName, int picType){
		String path = getPicPath(context, url, dirName, picType);
		File file = new File(path);
		
		InputStream in = null; 
		if (!file.exists()) {
			return null;//in = new BufferedInputStream(new FileInputStream(context.getResources().getDrawable(R.drawable.weibo_pic)));			
		}else{
			  
			try {     
				in = new BufferedInputStream(new FileInputStream(file));
			}catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}/*finally {     
				if (in != null) {       
					in.close();
					}   
				} 	
			}*/
			return in;
			//bm = BitmapFactory.decodeFile(path);
		}
	}

	public static InputStream getRequest(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000); // 5秒
		if (conn.getResponseCode() == 200) {
			return conn.getInputStream();
		}
		return null;
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}
	
	public static String formatDate(Date date) {
		return /*String.valueOf(date.getYear() + 2000 - 100) + "-"
				+ */String.valueOf(date.getMonth() + 1) + "-"
				+ String.valueOf(date.getDate()) + " "
				+ String.valueOf(date.getHours()) + ":"
				+ String.valueOf(date.getMinutes())/* + ":"
				+ String.valueOf(date.getSeconds())*/;
	}
	
	public static double getWeiboTextCount(String text) {
		double count = 0;
		for (int i = 0; i < text.length(); i++) {
			if (ENG_STRING.contains(String.valueOf(text.charAt(i)))) {
				count += 0.5;
            }else{
            	count += 1;
            }
		}
		
		return count;
	}
	
	public static boolean isSDCARDMounted(){
        String status = Environment.getExternalStorageState();
       
        if (status.equals(Environment.MEDIA_MOUNTED))
            return true;
        return false;
    }
}
